<!DOCTYPE html>
<html>

<head>
	<!-- 设置字符编码 -->
	<meta charset="UTF-8">
	<!-- 禁止移动端页面缩放 -->
	<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
	<!-- 阻止浏览器缓存页面内容 -->
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=8">
	<meta http-equiv="Expires" content="0">
	<meta http-equiv="Pragma" content="no-cache">
	<meta http-equiv="Cache-control" content="no-cache">
	<meta http-equiv="Cache" content="no-cache">
	<!-- 设置样式表 -->
	<title>校园帮帮</title>
	<link rel="stylesheet" href="/stylesheets/root.css">
	<link rel="stylesheet" href="/stylesheets/main.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
	<link rel="stylesheet" href="/stylesheets/main_bottom_line.css">
	<link rel="stylesheet" href="/stylesheets/like-button.css">
</head>

<body>
	<div class="window-box">
		<div class="main-box">
			<!-- 搜索框 -->
			<div class="search">
				<div class="search-box">
					<div class="signin">打卡</div>
					<div class="input-box">
						<input type="text">
						<div class="search-btn">
							<img src="/images/main/sousuo.png" alt="">
						</div>
					</div>
				</div>
			</div>
			<!-- 管理员全局通告 -->
			<div class="root-info">
				<div class="info">
					<img src="/images/main/tonggao.png" alt="">
					<span class="status">【官方消息】</span>
					<span class="text">发广告直接封禁账号！无论什么广告！</span>
				</div>
			</div>
			<!-- 校园论坛的入口 -->
			<div class="student-hub">
				<div class="hub-box">
					<div class="l-box">
						<div class="hub-icon"><img src="/images/main/baimao.png" alt=""></div>
						<div class="hub-icon"><img src="/images/main/heimao.png" alt=""></div>
					</div>
					<div class="r-box">
						<div>校园论坛入口</div>
						<div>进入>></div>
					</div>
				</div>
			</div>
			<!-- app内迷你功能 -->
			<div class="mini-apps">
				<!-- apps-box这个盒子里面存在很多的功能，后期可以使用js添加进去，这样可以实现动态加载 -->
				<div class="apps-box">
					<div class="app">
						<a href="/webpage_copy/index-schoolinfo.html">
							<img src="/images/main/benxiaotonzhi.png" alt="">
							<span class="app-name">本校通知</span>
						</a>
					</div>
					<div class="app">
						<a href="/webpage_copy/found_lost.html">
							<img src="/images/main/shiwuzhaoling.png" alt="">
							<span class="app-name">失物招领</span>
						</a>
					</div>
					<div class="app">
						<a href="/webpage_copy/index-didi.html">
							<img src="/images/main/xiaoyuandidi.png" alt="">
							<span class="app-name">校园滴滴</span>
						</a>
					</div>
					<div class="app">
						<a href="/webpage_copy/index-secretmail.html">
							<img src="/images/main/nimingtougao.png" alt="">
							<span class="app-name">匿名投稿</span>
						</a>
					</div>
					<div class="app">
						<a href="/webpage_copy/forum-more.html">
							<img src="/images/main/gengduo.png" alt="">
							<span class="app-name">更多</span>
						</a>
					</div>
				</div>
			</div>
			<!-- 校内动态板块 -->
			<div class="school-news">
				<div class="news-page">
					<!-- 这个功能放在后面做 由于前期没有足够的数据 -->
					<div class="news-box">
						<span>校内动态</span>
						<span>最 热</span>
						<span>最 新</span>
						<span>关 注</span>
					</div>
				</div>
				<div class="news-list"></div>
			</div>
		</div>
		<!-- 底部导航栏 -->
		<div class="bottom-line">
			<div class="bottom-line-box">
				<div class="page-main-page" data-jumpUrl="/main.html">
					<img src="/images/main/shouye.png" alt="">
					<p class="button_text">首页</p>
				</div>
				<div class="page-activity-page" data-jumpUrl="/webpage_copy/activity.html">
					<img src="/images/main/huodong.png" alt="">
					<p class="button_text">活动</p>
				</div>
				<div class="add-btn" data-jumpUrl="/forum/forum-edit.html">
					<img src="/images/main/jiahao.png" alt="">
				</div>
				<div class="page-message-page" data-jumpUrl="/webpage_copy/massage/list_massage.html">
					<img src="/images/main/xinxi.png" alt="">
					<p class="button_text">消息</p>
				</div>
				<div class="page-self-page" data-jumpUrl="/webpage_copy/my/my-updates.html">
					<img src="/images/main/wode.png" alt="">
					<p class="button_text">我的</p>
				</div>
			</div>
		</div>
	</div>
	<script>
		let offset = 2; //  因为初始显示0-2所以这里要从2开始
		const limit = 2; // 每次请求加载的帖子数量
		let loading = false; // 是否正在加载的标志
		let allPostsLoaded = false; // 是否所有帖子都已加载的标志
		let values = localStorage.getItem("jwt");
		const newsListDiv = document.querySelector('.news-list');
		// 本脚本的功能是使底部导航栏点击跳转链接可以生效
		const box = document.querySelector('.bottom-line-box');
		for (let i = 0; i < box.children.length; i++) {
			let tmp = box.children[i];
			console.log(tmp.dataset.jumpurl);
			if (tmp.dataset.jumpurl != "") {
				let jmp_a = document.createElement('a');
				jmp_a.href = tmp.dataset.jumpurl;
				tmp.addEventListener('click', () => {
					console.log(jmp_a);
					jmp_a.click();
				});
			}
		}

		// createPostElement会生div孩子
		function createPostElement(postData) {
			const postDiv = document.createElement('div');
			postDiv.className = 'new';
			postDiv.innerHTML = `
				<div class="user-line">
					<img class="user-icon" src=${postData.user_icon} alt="">
				<div class="user-name">${postData.username}</div>
				<div class="user-info">${postData.createTime}</div>
				<div class="bottom-drop">
					<div></div>
					<div></div>
				</div>
				</div>
				<a href="/webpage_copy/massage/reply_massage.html?postID=${postData.postID}">
				<div class="text-line">
					<div>${postData.intor}</div>
				</div>
				<div class="img-line">
				<div class="img-line-box">
					${postData.imgList ? `<img src="${postData.imgList}" style="float: left;">` : ''}
				</div>
				</div>
				</a>
				<div class="pinglun-dianzan-box">
				<div class="pinglun-box">
					<img src="/images/main/pinglun.png" alt="">${postData.comments}
				</div>

				<div class="like-container">
					${postData.user_upvoted ? `<button class="like-btn liked">` : '<button class="like-btn">'}
					<i class="fa fa-heart"></i>
					<span class="like-count" name="upvote${postData.postID}">${postData.upvotes}</span>
					</button>
				</div>
				</div> `;
			// 在这里为新创建的点赞按钮绑定事件监听器
			const likeBtn = postDiv.querySelector('.like-btn');
			const likeCount = postDiv.querySelector('.like-count');

			let liked = false;

			likeBtn.addEventListener('click', () => {
				liked = !liked;
				likeBtn.classList.toggle('liked');

				let data = {
					postID: postData.postID
				};
				fetch('/post/upvote', {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
						'Authorization': values // 设置Authorization头部，携带jwt令牌
					},
					body: JSON.stringify(data)
				})
					.then(response => {
						if (!response.ok) {
							throw new Error('error');
						}
						return response.json();
					})
					.then(a => {
						// 服务器返回的数据中有最新的点赞数
						const upvoteCount = a[0].UpvoteCount;
						const postID = a[0].postID;
						// 找到点赞数的<i>元素并更新其内容
						const likeElement = postDiv.querySelector(`[name="upvote${postID}"]`);
						if (likeElement) {
							likeElement.textContent = upvoteCount;
						}

						// 更新 postData 对象中的点赞数
						postData.upvotes = upvoteCount;
					})
					.catch(error => {
						// 这里是处理错误的地方
						console.error('There has been a problem with your fetch operation:', error);
					});
			});

			return postDiv;
		}

		function loadPosts(offset, limit) {
			if (loading || allPostsLoaded) {
				return;
			}
			loading = true;
			fetch(`/post/all?offset=${offset}&limit=${limit}`, {
				method: 'GET',
				headers: {
					'Authorization': values
				}
			})
			.then(response => {
				if (!response.ok) {
					throw new Error('Network response was not ok');
				}
				return response.json();
			})
			.then(posts => {
				if (posts.length < limit) {
					// 如果返回的帖子少于请求的数量，说明已经加载完所有帖子
					allPostsLoaded = true;
				}
				posts.forEach(element => {
					// ['imgList']是数据类型，得到的data是二进制所以要转为字符串
					element['imgList'] = element['imgList']['data']
						.map(code => String.fromCharCode(code)).join('');
					element['user_icon'] = element['user_icon']['data']
						.map(code => String.fromCharCode(code)).join('');
					element['createTime'] = element['createTime'].slice(0, 10) + ' ' + element['createTime'].slice(11, 16);

					const postElement = createPostElement(element);
					newsListDiv.appendChild(postElement);
				});
			})
			.catch(error => {
				console.error('There has been a problem with your fetch operation:', error);
			})
			.finally(() => {
				loading = false; // 更新加载状态
			});
		}

		function onScroll() {
			// 检查是否滚动到页面底部，并且没有正在加载的帖子
			if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 100 && !loading) {
				loadPosts(offset, limit);
				offset += 2; // 更新已加载的帖子数量
			}
		}

		window.addEventListener('scroll', onScroll);

		// 初始加载帖子
		loadPosts(0, limit);  // 初始显示从0-2

	</script>
</body>

</html>
